package com.marion.micro.app.common.response;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常返回定义
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 其他异常返回E_SERVER
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandler(HttpServletResponse response, Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        log.error("[exceptionHandler] error info = {}", e);
        return ResponseResult.builder()
                .code(AppError.E_SERVER.getCode())
                .message(AppError.E_SERVER.getMessage())
                .build();
    }

    /**
     * 处理手动抛出的异常, 400错误返回
     */
    @ExceptionHandler(ResponseException.class)
    public ResponseResult responseExceptionHandler(HttpServletResponse response, ResponseException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        return ResponseResult.builder()
                .code(e.getError().getCode())
                .message(e.getError().getMessage())
                .build();
    }

}
